<template>
    <div
        class="page_root"
        :key="queryUpdateFlag"
        data-page-name="员工绩效-定制化"
        data-page-identification="y_auhlddz3b2"
    >
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_i5vpkrwxor 自定义模板_91za6gac5d -->
            <a-modal
                :visible="ygState.permissionVisible"
                centered
                :mask-closable="false"
                :keyboard="false"
                width="1200px"
                :scroll="{ y: 600 }"
                @cancel="cancelPermission"
                @ok="handleSubmitPermission"
                :ok-button-props="{ loading: permissionLoading }"
            >
                <template #title>
                    <div class="permission-title">
                        <div>主管评分权限-{{ ygState.dateStr }}</div>
                        <a-space>
                            <a-button
                                type="primary"
                                :loading="downloadPermissionLoading"
                                @click="downPermissionTemplate"
                                v-permission="'3000000458_vid_6ds990onan'"
                                >下载权限模板</a-button
                            >
                            <a-upload
                                v-permission="'3000000458_vid_u7xty6s8l5'"
                                :show-upload-list="false"
                                :before-upload="handlerUpload"
                                accept=".xlsx,.ppt,.pdf,.PDF, image/*, .docx, .rp, .xls"
                            >
                                <a-button>
                                    <upload-outlined />
                                    导入权限模板
                                </a-button>
                            </a-upload>
                        </a-space>
                    </div>
                </template>
                <a-table
                    :columns="permissionColumns"
                    :data-source="ygState.permissionDataSource"
                    :scroll="{ y: 600 }"
                    :loading="ygState.permissionLoading"
                    bordered
                    :pagination="false"
                    row-key="id"
                >
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'userNameWithSemi'">
                            <div style="display: flex">
                                <a-select
                                    v-model:value="record.userNameList"
                                    mode="tags"
                                    style="width: 100%"
                                    placeholder="请输入用户并回车"
                                    :token-separators="[',', ';']"
                                    :options="record.userNameList.map(v => ({ label: v, value: v }))"
                                    allowClear
                                    showSearch
                                />
                            </div>
                        </template>
                    </template>
                </a-table>
            </a-modal>
            <div class="ygjx-div">
                <a-row :gutter="16">
                    <a-col :span="24">
                        <div class="right-div">
                            <span class="right-title">{{ ygState.dateStr }}绩效列表</span>
                            <a-row class="row-size" :gutter="24">
                                <a-col :span="4">
                                    <a-form-item label="月份">
                                        <a-date-picker
                                            v-model:value="ygState.filter.month"
                                            picker="month"
                                            value-format="YYYY-MM"
                                            style="width: 100%"
                                            :allowClear="false"
                                            :disabled-date="disabledDate"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-item label="部门">
                                        <a-select
                                            :placeholder="selectHolder"
                                            v-model:value="ygState.filter.departmentName"
                                            :options="ygState.departmentList"
                                            show-search
                                            :field-names="{ label: 'label', value: 'value' }"
                                            :filter-option="
                                                (input, option) => {
                                                    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-item label="团队成员">
                                        <a-select
                                            :placeholder="selectHolder"
                                            v-model:value="ygState.filter.userName"
                                            :options="ygState.peopleList"
                                            show-search
                                            :field-names="{ label: 'label', value: 'value' }"
                                            :filter-option="
                                                (input, option) => {
                                                    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                }
                                            "
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col
                                    class="row-size"
                                    :span="12"
                                    style="display: flex; justify-content: end; align-items: start"
                                >
                                    <div class="right-btn">
                                        <a-button type="primary" @click="getData()">查询</a-button>
                                        <a-button type="primary" ghost @click="resetTableData">重置</a-button>
                                        <a-button
                                            type="primary"
                                            v-permission="'3000000458_vid_71z9unjze7'"
                                            @click="showOrHiddenEdit"
                                            :loading="okLoading"
                                            >{{ ygState.isEdit ? '完成' : '编辑' }}</a-button
                                        >
                                        <a-button
                                            type="primary"
                                            v-permission="'3000000458_vid_8kblgrxikx'"
                                            @click="handleSubmitScore"
                                            :disabled="!isPrevMonth(ygState.filter.month)"
                                            :loading="submitLoading"
                                            >评分提交</a-button
                                        >
                                        <a-button
                                            type="primary"
                                            :disabled="!isPrevMonth(ygState.filter.month)"
                                            :loading="generateLoading"
                                            @click="handleGenerate"
                                            v-permission="'3000001093_vid_e8d1qz4ux7'"
                                            ><template #icon><user-add-outlined /></template>生成绩效</a-button
                                        >
                                        <a-button
                                            type="primary"
                                            v-permission="'3000000458_vid_hdcagdbknn'"
                                            @click="handlerUploadScore"
                                            :loading="exportLoading"
                                            >导出</a-button
                                        >
                                        <a-button
                                            type="primary"
                                            v-permission="'3000000458_vid_4m14s4lj4s'"
                                            @click="handleShowPermission"
                                            >主管评分权限</a-button
                                        >
                                    </div>
                                </a-col>
                            </a-row>
                            <div class="yg-table">
                                <a-table
                                    rowKey="id"
                                    bordered
                                    :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                                    :scroll="{ y: ygState.tableHeight }"
                                    :columns="displayColumns"
                                    :data-source="ygState.tableData"
                                    :loading="ygState.tableLoading"
                                    @resizeColumn="handleTaskResizeColumn"
                                    :pagination="false"
                                >
                                    <template #bodyCell="{ column, record, text, index }">
                                        <template v-if="column.dataIndex === 'numIndex'">
                                            {{ index + 1 }}
                                        </template>
                                        <!--                                      上级主管评分-->
                                        <template v-if="column.dataIndex === 'managerFraction'">
                                            <a-input-number
                                                v-model:value="record.managerFraction"
                                                v-if="ygState.isEdit"
                                                min="0"
                                                :precision="0"
                                            />
                                        </template>
                                        <!--                                      上级主管评分-->
                                        <!--                                      上级主管评分备注-->
                                        <template v-if="column.dataIndex === 'managerFractionDescription'">
                                            <a-textarea
                                                v-model:value="record.managerFractionDescription"
                                                v-if="ygState.isEdit"
                                            />
                                        </template>
                                        <!--                                      上级主管评分备注-->
                                        <!--                                      其他加减分-->
                                        <template v-if="column.dataIndex === 'otherFraction'">
                                            <a-input-number
                                                :precision="0"
                                                v-model:value="record.otherFraction"
                                                v-if="ygState.isEdit"
                                            />
                                        </template>
                                        <!--                                      其他加减分-->
                                        <!--                                      其他加减分详情-->
                                        <template v-if="column.dataIndex === 'otherFractionDescription'">
                                            <a-textarea
                                                v-model:value="record.otherFractionDescription"
                                                v-if="ygState.isEdit"
                                            />
                                        </template>
                                        <!--                                      其他加减分详情-->
                                        <template v-if="column.dataIndex === 'behaviorFractionDescription'">
                                            <a-tooltip
                                                @mouseenter="handlerGetStandard(text)"
                                                :overlay-style="tooltipStyle"
                                                placement="right"
                                            >
                                                <template #title>
                                                    <p
                                                        style="margin: 0"
                                                        v-for="(item, index) in behaviorFractionDescriptionList"
                                                        :key="index"
                                                        >{{ item }}</p
                                                    >
                                                </template>
                                                <div class="behavior-div"> {{ text }}</div>
                                            </a-tooltip>
                                        </template>
                                        <template v-if="column.dataIndex === 'resultFractionDescription'">
                                            <a-tooltip
                                                @mouseenter="handlerGetResult(text)"
                                                :overlay-style="tooltipStyle"
                                                placement="right"
                                            >
                                                <template #title>
                                                    <p
                                                        style="margin: 0"
                                                        v-for="(item, index) in resultFractionDescriptionList"
                                                        :key="index"
                                                        >{{ item }}</p
                                                    >
                                                </template>
                                                <div class="result-div"> {{ text }}</div>
                                            </a-tooltip>
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </div>
                    </a-col>
                </a-row>
            </div>
            <!-- end vid_i5vpkrwxor 自定义模板_91za6gac5d -->
            <!-- begin vid_kq2wz745ys 容器_b5jk3uyrfp -->
            <al-box v-if="false" class="vid_kq2wz745ys">
                <!-- begin vid_u7xty6s8l5 绩效-导入权限模板 -->
                <a-button v-permission="'3000000458_vid_u7xty6s8l5'" class="vid_u7xty6s8l5">
                    绩效-导入权限模板
                </a-button>
                <!-- end vid_u7xty6s8l5 绩效-导入权限模板 -->
                <!-- begin vid_71z9unjze7 绩效-编辑/完成 -->
                <a-button v-permission="'3000000458_vid_71z9unjze7'" class="vid_71z9unjze7"> 绩效-编辑/完成 </a-button>
                <!-- end vid_71z9unjze7 绩效-编辑/完成 -->
                <!-- begin vid_hdcagdbknn 绩效-导出绩效分数 -->
                <a-button v-permission="'3000000458_vid_hdcagdbknn'" class="vid_hdcagdbknn">
                    绩效-导出绩效分数
                </a-button>
                <!-- end vid_hdcagdbknn 绩效-导出绩效分数 -->
                <!-- begin vid_4m14s4lj4s 绩效-主观评分权限 -->
                <a-button v-permission="'3000000458_vid_4m14s4lj4s'" class="vid_4m14s4lj4s">
                    绩效-主观评分权限
                </a-button>
                <!-- end vid_4m14s4lj4s 绩效-主观评分权限 -->
                <!-- begin vid_6ds990onan 绩效-下载权限模板 -->
                <a-button v-permission="'3000000458_vid_6ds990onan'" class="vid_6ds990onan">
                    绩效-下载权限模板
                </a-button>
                <!-- end vid_6ds990onan 绩效-下载权限模板 -->
            </al-box>
            <!-- end vid_kq2wz745ys 容器_b5jk3uyrfp -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    import permissionForm from '@/views/system/flow/components/propertyPanel/components/permissionForm.vue'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        const lastMonth = dayjs().subtract(1, 'month')
        // 格式化时间为 yyyy-mm
        ygState.filter.month = lastMonth.format('YYYY-MM')
        ygState.dateStr = lastMonth.format('YYYY年MM月')
        getData()
    })
    function isCurrentMonth() {
        return dayjs(ygState.filter.month).isSame(dayjs(), 'month')
    }
    const inputHolder = '请输入'
    const selectHolder = '请选择'
    const ygState = reactive({
        expandedKeys: [],
        selectedKeys: [],
        checkedKeys: [],
        searchValue: '',
        dateStr: '',
        filter: {
            userName: undefined,
            departmentName: undefined,
            month: undefined
        },
        tableLoading: false,
        treeData: [],
        selected: {},
        projectNameList: [],
        tableData: [],
        peopleList: [],
        selectedRowKeys: [],
        exportScoreVisible: false,
        addOrReduceVisible: false,
        giveScoreVisible: false,
        fileList: [],
        staffType: 'DEPARTMENT',
        isTableIn: false,
        permissionVisible: false,
        permissionTitle: '',
        permissionDataSource: [],
        isEdit: false,
        editLoading: false,
        permissionLoading: false,
        tableHeight: 600,
        showColumns: []
    })
    const columnMap = {
        'user_name': 'userName',
        'department_name': 'departmentName',
        'result_fraction': 'resultFraction',
        'result_fraction_description': 'resultFractionDescription',
        'behavior_fraction': 'behaviorFraction',
        'behavior_fraction_description': 'behaviorFractionDescription',
        'leader': 'leader',
        'rating_status': 'ratingStatus',
        'manager_fraction': 'managerFraction',
        'manager_fraction_description': 'managerFractionDescription',
        'other_fraction': 'otherFraction',
        'other_fraction_description': 'otherFractionDescription',
        'final_fraction': 'finalFraction'
    }
    const overlayStyle = {
        maxWidth: 'unset'
    }
    const columns = ref([
        { title: '序号', dataIndex: 'numIndex', align: 'center', width: 100, resizable: true, visible: true },

        {
            title: '人员姓名',
            dataIndex: 'userName',
            width: 100,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '部门',
            dataIndex: 'departmentName',
            width: 100,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '项目结果分',
            dataIndex: 'resultFraction',
            width: 120,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '项目结果分详情',
            dataIndex: 'resultFractionDescription',
            width: 140,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '项目过程分',
            dataIndex: 'behaviorFraction',
            width: 120,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '项目过程分详情',
            dataIndex: 'behaviorFractionDescription',
            width: 140,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '上级主管',
            dataIndex: 'leader',
            width: 125,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '评分状态',
            dataIndex: 'ratingStatus',
            width: 125,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '上级主管评分',
            dataIndex: 'managerFraction',
            width: 125,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '上级主管评分备注',
            dataIndex: 'managerFractionDescription',
            width: 155,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '其他加减分',
            dataIndex: 'otherFraction',
            width: 120,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '其他加减分备注',
            dataIndex: 'otherFractionDescription',
            width: 140,
            align: 'center',
            ellipsis: true,
            resizable: true,
            visible: false
        },
        {
            title: '合计分数',
            dataIndex: 'finalFraction',
            width: 130,
            align: 'center',
            ellipsis: true,
            resizable: true,
            fixed: 'right',
            customCell: () => {
                return {
                    style: {
                        color: '#262626',
                        fontWeight: 'bold'
                    }
                }
            },
            visible: false
        }
        // { title: '操作', dataIndex: 'operate', width: 380, align: 'center', ellipsis: true, fixed: 'right' }
    ])
    const displayColumns = computed(() => {
        // 后端返回字段映射成 dataIndex
        const dataIndexesFromServer = ygState.showColumns.map(colKey => columnMap[colKey]).filter(Boolean)

        return columns.value.filter(col => {
            // 必须展示列直接返回 true
            if (col.visible) return true

            // 其他列根据后端返回判断
            return dataIndexesFromServer.includes(col.dataIndex)
        })
    })

    watch(
        () => ygState.filter.month,
        () => {
            if (ygState.filter.month) {
                const formattedDate = dayjs(ygState.filter.month, 'YYYY-MM').format('YYYY年MM月')
                ygState.dateStr = formattedDate
            }
        },
        { deep: true }
    )

    function resetTableData() {
        ygState.filter = {
            userName: undefined,
            departmentName: undefined,
            month: undefined
        }
        const lastMonth = dayjs().subtract(1, 'month')

        // 格式化时间为 yyyy-mm
        ygState.filter.month = lastMonth.format('YYYY-MM')

        ygState.dateStr = lastMonth.format('YYYY年MM月')
        getData()
    }

    const isFirst = ref(true)
    function getData() {
        ygState.tableLoading = true
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/list?userName=${ygState.filter.userName || ''}&month=${
                ygState.filter.month
            }&departmentName=${ygState.filter.departmentName || ''}`
        )
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                if (isFirst.value) {
                    ygState.peopleList = data.data.userMonthlyPerformanceList.map(item => {
                        return {
                            label: item.userName,
                            value: item.userName
                        }
                    })
                    ygState.departmentList = [
                        ...new Map(
                            data.data.userMonthlyPerformanceList.map(item => [
                                item.departmentName,
                                {
                                    label: item.departmentName,
                                    value: item.departmentName
                                }
                            ])
                        ).values()
                    ]
                }
                isFirst.value = false
                ygState.tableData = data.data.userMonthlyPerformanceList
                if (!data.data.columnAuth || data.data.columnAuth.lenth == 0) {
                    ygState.showColumns = [
                        'id',
                        'monthly',
                        'user_name',
                        'leader',
                        'ratingStatus',
                        'department_name',
                        'result_fraction',
                        'result_fraction_description',
                        'behavior_fraction',
                        'behavior_fraction_description',
                        'manager_fraction',
                        'manager_fraction_description',
                        'other_fraction',
                        'other_fraction_description',
                        'final_fraction',
                        'del_flag'
                    ]
                } else {
                    ygState.showColumns = data.data.columnAuth
                }
            })
            .finally(() => {
                ygState.tableLoading = false
            })
    }
    function formatData(data) {
        return data.map(project => {
            project.taskDtoList = groupMilepostData(project.taskDtoList)
            return project
        })
    }

    // 格式化
    function groupMilepostData(data) {
        let currentProjectMilepost = ''
        return data.map((item, index) => {
            if (currentProjectMilepost !== item.projectMilepost) {
                currentProjectMilepost = item.projectMilepost
                let rowSpan = 0
                for (let i = 0; i < data.length; i++) {
                    if (i >= index) {
                        if (currentProjectMilepost === data[i].projectMilepost) {
                            rowSpan += 1
                        } else {
                            break
                        }
                    }
                }
                item.rowSpan = rowSpan
            } else {
                item.rowSpan = 0
            }
            return item
        })
    }

    //

    const downloadPermissionLoading = ref(false) //     下载模板
    function downPermissionTemplate({ url, name }) {
        downloadPermissionLoading.value = true
        get('/solution-ppm/api/v2/built-in-system-ppm/performance_investment/template/download', null, {
            responseType: 'blob',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .then(res => {
                downloadExcel(res, '权限模板.xlsx')
            })
            .finally(() => {
                downloadPermissionLoading.value = false
            })
    }

    function downloadExcel(response, name) {
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
        return href
    }

    function handlerUploadScore() {
        exportLoading.value = true
        post(
            `/solution-ppm/api/v2/built-in-system-ppm/emgf/v2/export`,
            { month: ygState.filter.month },
            {
                responseType: 'arraybuffer'
            }
        )
            .then(res => {
                downloadExcel(res, '绩效分数.xlsx')
                ygState.fileList = []
            })
            .finally(() => {
                exportLoading.value = false
            })
    }
    const generateLoading = ref(false)
    // 生成绩效
    function handleGenerate() {
        generateLoading.value = true
        put('/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/generate')
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
                getData()
            })
            .finally(() => {
                generateLoading.value = false
            })
    }
    function handlerUpload(file) {
        // 检查文件类型
        if (!/\.xlsx?$/.test(file.name.toLowerCase())) {
            message.error('只能上传 xlsx 或 xls 文件')
            return false
        }

        const formData = new FormData()
        formData.append('file', file)

        post(
            `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/import_user/${ygState.filter.month}`,
            formData
        )
            .then(res => {
                if (res.code === 200) {
                    message.success('上传成功')
                    getPermissionData()
                } else {
                    message.error(res.message || '上传失败')
                }
            })
            .catch(() => {
                message.error('上传接口异常')
            })

        return false
    }

    function getPermissionData() {
        ygState.permissionLoading = true
        get(`/solution-ppm/api/v2/built-in-system-ppm/performance_investment/import_user/${ygState.filter.month}`)
            .then(data => {
                if (data.code === 200) {
                    ygState.permissionDataSource = data.data
                } else {
                    message.error(data.message)
                }
            })
            .finally(() => {
                ygState.permissionLoading = false
            })
    }

    const exportLoading = ref(false)
    const disabledDate = current => {
        if (!current) {
            return false // 如果没有当前日期，不禁用
        }

        const now = dayjs() // 获取当前时间
        const currentYear = now.year() // 获取当前年份
        const currentMonth = now.month() // 获取当前月份 (0-11)

        // 核心逻辑：如果选择的日期年份大于当前年份，则禁用（因为月份必然更晚）
        if (current.year() > currentYear) {
            return true
        }

        // 如果选择的日期年份等于当前年份，则判断其月份是否大于当前月份，大于则禁用
        if (current.year() === currentYear) {
            return current.month() >= currentMonth
        }

        // 其余情况（年份小于当前年份，即往年所有月份），都不禁用，即可选
        return false
    }
    function handleTaskResizeColumn(w, col) {
        console.log(w)
        console.log(col, 'col')
        // 根据列标题来确定不同的 div
        const width = w - 10
        // let div = null
        // if (col.title === 'PPM行为分详情') {
        //     div = document.querySelectorAll('.behavior-div')
        // } else if (col.title.includes('项目结果分详情')) {
        //     div = document.querySelectorAll('.result-div')
        // } else if (col.title === '总目标') {
        //     div = document.querySelectorAll('.default-gant-title-total')
        // } else if (col.title === '子目标') {
        //     div = document.querySelectorAll('.default-gant-title-zmb')
        // }
        // console.log(div, 'div')
        // // 如果找到了对应的 div，更新其宽度
        // if (div.length > 0) {
        //     div.forEach(item => {
        //         item.style.width = `${width}px`
        //     })
        // }
        col.width = w
    }

    const behaviorFractionDescriptionList = ref([])
    const resultFractionDescriptionList = ref([])
    // 新-模板项目审核标准格式
    function handlerGetStandard(text) {
        behaviorFractionDescriptionList.value = text?.split(/[,;；]/)
    }
    function handlerGetResult(text) {
        resultFractionDescriptionList.value = text?.split(/[,;；]/)
    }
    const onSelectChange = selectedRowKeys => {
        ygState.selectedRowKeys = selectedRowKeys
    }
    const tooltipStyle = {
        maxWidth: '600px',
        maxHeight: '600px',
        overflowY: 'auto'
    }
    const permissionColumns = ref([
        {
            title: '部门',
            dataIndex: 'department',
            align: 'center'
        },
        {
            title: '评分主管',
            dataIndex: 'leader',
            align: 'center'
        },
        {
            title: '下辖组员',
            dataIndex: 'userNameWithSemi',
            align: 'center'
        }
    ])
    function handleShowPermission() {
        getPermissionData()
        ygState.permissionVisible = true
        message.info('导入权限模板后将对已生成的操作关系进行覆盖')
        ygState.permissionTitle = `主管评分权限${ygState.dateStr}`
    }
    const okLoading = ref(false)
    function showOrHiddenEdit() {
        okLoading.value = true
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/parameter/judge_time_control/${ygState.filter.month}/LEADER_RATING`
        ).then(data => {
            okLoading.value = false
            if (!data.data) {
                message.info('请在评分起止时间内操作')
                okLoading.value = false
                return
            } else {
                okLoading.value = false
                if (!ygState.isEdit) {
                    ygState.isEdit = true
                } else {
                    okLoading.value = true
                    put(
                        `/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/score_changes_batch/${ygState.filter.month}`,
                        ygState.tableData
                    )
                        .then(data => {
                            if (data.code !== 200) {
                                message.error(data.message)
                                return
                            }
                            message.success(`${data.message} 确认无误后请及时提交评分`)
                            ygState.isEdit = false
                            getData()
                        })
                        .finally(() => {
                            okLoading.value = false
                        })
                }
            }
        })
    }
    const submitLoading = ref(false)
    // 评分提交
    function handleSubmitScore() {
        submitLoading.value = true
        put(`/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/rating_submit/${ygState.filter.month}`)
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
                getData()
            })
            .finally(() => {
                submitLoading.value = false
            })
    }
    const headerOffset = ref(100)
    const calcTableHeight = () => {
        ygState.tableHeight = window.innerHeight - 180 - headerOffset.value
    }

    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    // monthStr 是 yyyy-MM 格式
    const isPrevMonth = monthStr => {
        if (!monthStr) return false
        // 只允许前一个月
        return dayjs(monthStr, 'YYYY-MM').isSame(dayjs().subtract(1, 'month'), 'month')
    }

    function cancelPermission() {
        ygState.permissionVisible = false
        ygState.permissionDataSource = []
    }
    const permissionLoading = ref(false)
    function handleSubmitPermission() {
        // 校验重复人员
        const nameMap = new Map()
        ygState.permissionDataSource.forEach(item => {
            item.userNameList?.forEach(name => {
                if (!nameMap.has(name)) {
                    nameMap.set(name, [])
                }
                nameMap.get(name).push(item.department || '未知部门')
            })
        })

        const duplicates = []
        nameMap.forEach((depts, name) => {
            if (depts.length > 1) {
                duplicates.push(`${name} 出现在部门：${[...new Set(depts)].join('，')}`)
            }
        })

        if (duplicates.length > 0) {
            message.error({
                content: `以下人员重复：\n${duplicates.join('\n')}`,
                duration: 6
            })
            permissionLoading.value = false
            return
        }
        permissionLoading.value = true
        put(
            `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/import_user/${ygState.filter.month}`,
            ygState.permissionDataSource
        )
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
                cancelPermission()
                getData()
            })
            .finally(() => {
                permissionLoading.value = false
            })
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .vid_kq2wz745ys {
        padding-top: 24px;
        padding-bottom: 24px;
        background-color: #a70404;
    }
    .vid_u7xty6s8l5 {
        box-shadow: 0px 0px 0px 0px;
    }
    .vid_71z9unjze7 {
        box-shadow: 0px 0px 0px 0px;
    }
    .vid_4m14s4lj4s {
        box-shadow: 0px 0px 0px 0px;
    }
    /*样式*/
    .ygjx-div {
        width: 100%;
        height: 100%;
        background-color: #fff;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .right-div {
        height: 100%;
        min-height: 800px;
        background-color: #fff;
    }

    .right-div {
        padding: 20px 24px;
    }

    .right-title {
        display: inline-block;
        font-size: 18px;
        color: #3875ff;
        font-weight: 600;
        margin-bottom: 12px;
    }

    .row-size {
        height: 32px;
        margin-bottom: 16px;
    }

    .yg-table :deep(.@{ant-prefix}-table-thead) > tr {
        height: 40px;
    }

    .yg-table :deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #3875ff;
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 600;
        color: #ffffff;
        border-bottom: 1px solid #3875ff;
        padding: 8px 16px;
    }

    .yg-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        padding: 8px 16px;
        word-break: break-all;

        .cell-wrapper {
            padding: 0 16px;
        }
    }

    /*绩效详情*/

    .short {
        height: 110px;
    }
    .behavior-div,
    .result-div {
        width: 130px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .permission-title {
        display: flex;
        justify-content: space-between;
        padding-right: 24px;
        align-items: center;
        font-weight: 600;
        margin-bottom: 16px;
    }
    .right-btn {
        display: flex;
        gap: 8px;
    }
</style>
